﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using WebApi.Domain;
using WebApi.Interface;

namespace WebApi.Realize
{
    public class EfRepository<T> : IRespository<T> where T : BaseEntity
    {

        protected readonly Admin3000 db;

        private DbSet<T> _entity;

        private DbSet<T> Entity
        {
            get
            {
                if (_entity == null)
                {
                    _entity = db.Set<T>();

                }
                return  _entity;
            }
        }

        public IQueryable<T> Table => Entity;

        public EfRepository(Admin3000 dbContext) 
        {
            db = dbContext;
        }


        public void Deleted(T entity)
        {
            this._entity.Remove(entity);
            db.SaveChanges();
        }

        public void Deleted(int id)
        {
            var row = Table.Where(x => x.Id == id).FirstOrDefault();
            Deleted(row);
            db.SaveChanges();
        }


        public T GetbyId(int id)
        {
            return _entity.Where(x => x.Id == id).FirstOrDefault();

            

        }       

        public void Insert(T entity)
        {
            _entity.Add(entity);
            db.SaveChanges();
        }

        public void MoreInsert(IEnumerable<T> list)
        {
            _entity.Add((T)list);
            db.SaveChanges();
        }

        public void Update(T entity)
        {
            _entity.Update(entity);
            db.SaveChanges();
        }
    }
}
